package gisc.gov.vn.dev.gui;

import gisc.gov.vn.dev.core.IGiscSingletonInfo;
import gisc.gov.vn.dev.dataManager.GiscQueryFilterBuilder;
import gisc.gov.vn.dev.dataManager.IGiscQueryFilter;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.iver.andami.ui.mdiManager.IWindow;
import com.iver.andami.ui.mdiManager.SingletonWindow;
import com.iver.andami.ui.mdiManager.WindowInfo;
import com.iver.cit.gvsig.fmap.drivers.IConnection;
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class GiscChangePassPanel extends GiscPanel
{

	private static final long serialVersionUID = 1L;
	protected ProjectTable model = null;
	public GiscLoginPanel fLogin =null ;
	protected IGiscSingletonInfo info = null;
	private IConnection conn = null;  //  @jve:decl-index=0:
	public int id;
	private JLabel jLabel = null;
	private JTextField txtUser = null;
	private JLabel jLabel1 = null;
	private JPasswordField txtPassCu = null;
	private JLabel jLabel2 = null;
	private JPasswordField txtPassMoi = null;
	private JLabel jLabel3 = null;
	private JPasswordField txtPassMoiNhapLai = null;
	private JPanel jPanel = null;
	private JButton btnOk = null;
	private JButton btnReset = null;
	public String dburl = "";//"jdbc:postgresql://192.168.8.107/PCCC";  //  @jve:decl-index=0:
	public String dbuser = "";//"postgres"//;  //  @jve:decl-index=0:
	public String dbpass = "";//"postgres";  //  @jve:decl-index=0:
	private JLabel lblCapsLock = null;
	/**
	 * This method initializes 
	 * 
	 */
	public GiscChangePassPanel() {
		super();
		initialize();
		ConnectDB(null);
		LoadUser();
	}
	public GiscChangePassPanel(IGiscSingletonInfo loginPanel)
	{
		super();
		initialize();
		ConnectDB(loginPanel);
		LoadUser();
	}

	/**
	 * This method initializes this
	 * 
	 */
	private void initialize() {
        GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
        gridBagConstraints10.gridx = 1;
        gridBagConstraints10.anchor = GridBagConstraints.EAST;
        gridBagConstraints10.gridy = 4;
        lblCapsLock = new JLabel();
        lblCapsLock.setText("");
        GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
        gridBagConstraints11.gridx = 0;
        gridBagConstraints11.gridwidth = 3;
        gridBagConstraints11.fill = GridBagConstraints.BOTH;
        gridBagConstraints11.gridy = 5;
        GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
        gridBagConstraints8.fill = GridBagConstraints.BOTH;
        gridBagConstraints8.gridy = 3;
        gridBagConstraints8.weightx = 1.0;
        gridBagConstraints8.insets = new Insets(0, 0, 0, 3);
        gridBagConstraints8.gridx = 1;
        GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
        gridBagConstraints7.gridx = 0;
        gridBagConstraints7.fill = GridBagConstraints.BOTH;
        gridBagConstraints7.insets = new Insets(0, 3, 0, 0);
        gridBagConstraints7.gridy = 3;
        jLabel3 = new JLabel();
        jLabel3.setText("Nhập lại mật khẩu");
        GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
        gridBagConstraints6.fill = GridBagConstraints.BOTH;
        gridBagConstraints6.gridy = 2;
        gridBagConstraints6.weightx = 1.0;
        gridBagConstraints6.insets = new Insets(0, 0, 3, 3);
        gridBagConstraints6.gridx = 1;
        GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
        gridBagConstraints5.gridx = 0;
        gridBagConstraints5.fill = GridBagConstraints.BOTH;
        gridBagConstraints5.insets = new Insets(0, 3, 3, 0);
        gridBagConstraints5.gridy = 2;
        jLabel2 = new JLabel();
        jLabel2.setText("Mật khẩu mới");
        GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
        gridBagConstraints4.fill = GridBagConstraints.BOTH;
        gridBagConstraints4.gridy = 1;
        gridBagConstraints4.weightx = 1.0;
        gridBagConstraints4.insets = new Insets(0, 0, 3, 3);
        gridBagConstraints4.gridx = 1;
        GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
        gridBagConstraints3.gridx = 0;
        gridBagConstraints3.fill = GridBagConstraints.BOTH;
        gridBagConstraints3.insets = new Insets(0, 3, 3, 0);
        gridBagConstraints3.gridy = 1;
        jLabel1 = new JLabel();
        jLabel1.setText("Mật khẩu cũ");
        GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
        gridBagConstraints2.fill = GridBagConstraints.BOTH;
        gridBagConstraints2.gridy = 0;
        gridBagConstraints2.weightx = 1.0;
        gridBagConstraints2.insets = new Insets(0, 0, 3, 3);
        gridBagConstraints2.gridx = 1;
        GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
        gridBagConstraints1.gridx = 0;
        gridBagConstraints1.fill = GridBagConstraints.BOTH;
        gridBagConstraints1.insets = new Insets(0, 3, 3, 0);
        gridBagConstraints1.gridy = 0;
        jLabel = new JLabel();
        jLabel.setText("Tài khoản");
        this.setLayout(new GridBagLayout());
        this.setSize(new Dimension(372, 203));
        //this.setTitle("Thay doi mat khau");
        this.setBorder(BorderFactory.createTitledBorder(null, "Thông tin người dùng", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51)));
        this.add(jLabel, gridBagConstraints1);
        this.add(getTxtUser(), gridBagConstraints2);
        this.add(jLabel1, gridBagConstraints3);
        this.add(getTxtPassCu(), gridBagConstraints4);
        this.add(jLabel2, gridBagConstraints5);
        this.add(getTxtPassMoi(), gridBagConstraints6);
        this.add(jLabel3, gridBagConstraints7);
        this.add(getTxtPassMoiNhapLai(), gridBagConstraints8);
        this.add(getJPanel(), gridBagConstraints11);
        this.add(lblCapsLock, gridBagConstraints10);
			
	}
	public void ConnectDB(IGiscSingletonInfo loginPanel)  {
		
		try
		{
			this.info= loginPanel;
			dburl = info.GetDbUrl();//"jdbc:postgresql://192.168.8.107/PCCC";
			dbuser = info.GetDbUserName();//"postgres"//;
			dbpass = info.GetDbPass();//"postgres";
			//Class.forName("org.postgresql.Driver");
			//conn = ConnectionFactory.createConnection("jdbc:postgresql://" + fLogin.dburl + "/TGRQ11",fLogin.dbuser,fLogin.dbpass );
		}
		catch(Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.toString());
			JOptionPane.showMessageDialog(null,"Hãy đăng nhập hệ thống");
						}
	}
	public WindowInfo getWindowInfo() {
		WindowInfo vi = new WindowInfo(WindowInfo.ICONIFIABLE);
		vi.setTitle("Thay đổi mật khẫu");
		return vi;
	}

	public Object getWindowModel() {
		// TODO Auto-generated method stub
		return model;
	}

	
	public void windowActivated() {
		// TODO Auto-generated method stub
		
	}

	public void windowClosed() {
		// TODO Auto-generated method stub
		
	}


	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	public void LoadUser()
	{
		ConnectDB(info);
		try
		{
			JOptionPane.showMessageDialog(null, info.GetDbName());
			IGiscQueryFilter queryFilter = new GiscQueryFilterBuilder()
			.UserName(info.GetDbUserName())
			.Pass(info.GetDbPass())
			.Db(info.GetDbUrl())
			.Sql("select id,username from users where username = '" + info.GetDbUserName() + "';")
			.BuildQuery();
		
			queryFilter.Excute();
			ResultSet r= queryFilter.GetResult();
			while(r.next())
			{
				id=r.getInt(1);
				txtUser.setText(r.getString(2));
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			JOptionPane.showMessageDialog(null, e1);
		}
//				try {
//					 Class.forName("org.postgresql.Driver");
//					  Connection c = DriverManager.getConnection(dburl,dbuser,dbpass);
//					   Statement st = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);				
//					String sqlkt = "select id,username from users where username = '" + fLogin.GetUser() + "';";
// 					ResultSet rs = st.executeQuery(sqlkt);
//				while (rs.next())
//				{
//					id=rs.getInt(1);
//					txtUser.setText(rs.getString(2));
//								
//				}
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				JOptionPane.showMessageDialog(null, e);
//
//			}
		//-------
//			if(txtNhom.getText() == null || txtNhom.getText().equals("")){
//			try {
//				Statement st = ((ConnectionJDBC)conn).getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
//				((ConnectionJDBC)conn).getConnection().setAutoCommit(true);
//				String sqlkt = "SELECT uid, username, quyen,thoihan FROM nguoidung where username = '" + lg.dbuser + "';";
//				
//				ResultSet rs = st.executeQuery(sqlkt);
//
//				while (rs.next())
//				{
//					id=rs.getInt(1);
//					txtUser.setText(rs.getString(2));
//					txtQuyen.setText(rs.getString(3));
//					txtDate.setText(rs.getString(4));
//					
//				}
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				JOptionPane.showMessageDialog(null, e);
//
//			}}
	}

	public String MaPass(String password){
		String passhash = null;
		  try {
			   
			MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm
			   
			   mdEnc.update(password.getBytes(), 0, password.length());
			   
			   passhash = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string    
		 
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return passhash;
		
	}

	@Override
	public Object getWindowProfile() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * This method initializes txtUser	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTxtUser() {
		if (txtUser == null) {
			txtUser = new JTextField();
			txtUser.setEditable(false);
		}
		return txtUser;
	}

	/**
	 * This method initializes txtPassCu	
	 * 	
	 * @return javax.swing.JPasswordField	
	 */
	private JPasswordField getTxtPassCu() {
		if (txtPassCu == null) {
			txtPassCu = new JPasswordField();
			txtPassCu.addKeyListener( new KeyListener() {   
				public void keyTyped(java.awt.event.KeyEvent e) {    
				      boolean state= Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
				      if(state == true){
				      	lblCapsLock.setText("<HTML><FONT COLOR = Red>CapsLock is ON.</FONT></HTML>");
				      	txtPassCu.setText("");
				      	txtPassCu.requestFocus();
				      }
				      else 
				    	  lblCapsLock.setText("");
				}
				   public void keyPressed( KeyEvent e) {
					   
				   }

				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub
					 boolean state= Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
				      if(state == true){
				      	lblCapsLock.setText("<HTML><FONT COLOR = Red>CapsLock is ON.</FONT></HTML>");
				      	txtPassCu.setText("");
				      	txtPassCu.requestFocus();
				      }
				      else 
				    	  lblCapsLock.setText("");
				}

			
				} );
		}
		return txtPassCu;
	}

	/**
	 * This method initializes txtPassMoi	
	 * 	
	 * @return javax.swing.JPasswordField	
	 */
	private JPasswordField getTxtPassMoi() {
		if (txtPassMoi == null) {
			txtPassMoi = new JPasswordField();
			txtPassMoi.addKeyListener( new KeyListener() {   
				public void keyTyped(java.awt.event.KeyEvent e) {    
				      boolean state= Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
				      if(state == true){
				      	lblCapsLock.setText("<HTML><FONT COLOR = Red>CapsLock is ON.</FONT></HTML>");
				      	txtPassMoi.setText("");
				      	txtPassMoi.requestFocus();
				      }
				      else 
				    	  lblCapsLock.setText("");
				}
				   public void keyPressed( KeyEvent e) {
					   
				   }

				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub
					 boolean state= Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
				      if(state == true){
				      	lblCapsLock.setText("<HTML><FONT COLOR = Red>CapsLock is ON.</FONT></HTML>");
				      	txtPassMoi.setText("");
				      	txtPassMoi.requestFocus();
				      }
				      else 
				    	  lblCapsLock.setText("");
				}

			
				} );
		}
		return txtPassMoi;
	}

	/**
	 * This method initializes txtPassMoiNhapLai	
	 * 	
	 * @return javax.swing.JPasswordField	
	 */
	private JPasswordField getTxtPassMoiNhapLai() {
		if (txtPassMoiNhapLai == null) {
			txtPassMoiNhapLai = new JPasswordField();
			txtPassMoiNhapLai.addKeyListener( new KeyListener() {   
				public void keyTyped(java.awt.event.KeyEvent e) {    
				      boolean state= Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
				      if(state == true){
				      	lblCapsLock.setText("<HTML><FONT COLOR = Red>CapsLock is ON.</FONT></HTML>");
				      	txtPassMoiNhapLai.setText("");
				      	txtPassMoiNhapLai.requestFocus();
				      }
				      else 
				    	  lblCapsLock.setText("");
				}
				   public void keyPressed( KeyEvent e) {
					   
				   }

				public void keyReleased(KeyEvent arg0) {
					// TODO Auto-generated method stub
					 boolean state= Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
				      if(state == true){
				      	lblCapsLock.setText("<HTML><FONT COLOR = Red>CapsLock is ON.</FONT></HTML>");
				      	txtPassMoiNhapLai.setText("");
				      	txtPassMoiNhapLai.requestFocus();
				      }
				      else 
				    	  lblCapsLock.setText("");
				}

			
				} );
		}
		return txtPassMoiNhapLai;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.gridx = 1;
			gridBagConstraints9.insets = new Insets(3, 3, 0, 0);
			gridBagConstraints9.fill = GridBagConstraints.BOTH;
			gridBagConstraints9.gridy = 0;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 0;
			gridBagConstraints.fill = GridBagConstraints.BOTH;
			gridBagConstraints.insets = new Insets(3, 0, 0, 0);
			gridBagConstraints.gridy = 0;
			jPanel = new JPanel();
			jPanel.setLayout(new GridBagLayout());
			//.setBorder(BorderFactory.createTitledBorder(null, "Điểm kinh doanh", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51)));

			jPanel.add(getBtnOk(), gridBagConstraints);
			jPanel.add(getBtnReset(), gridBagConstraints9);
		}
		return jPanel;
	}

	/**
	 * This method initializes btnOk	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnOk() {
		if (btnOk == null) {
			btnOk = new JButton();
			btnOk.setText("Ok");
			btnOk.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try {
						Class.forName("org.postgresql.Driver");
						Connection c = DriverManager.getConnection(dburl,dbuser ,dbpass);
		    			Statement st = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);				

						String SelectSQL = "select pass from users where id='"+id+"'";
						
						ResultSet rs = st.executeQuery(SelectSQL);
						String pass = "";
						while (rs.next())
						{
							pass = rs.getString(1);
							
						}
						
						if (txtPassMoi.getText() == null || txtPassMoi.getText() == "")
						{
							JOptionPane.showMessageDialog(null, "Mật khẩu không thể trống");
							return;
						}
						if (pass.trim().equals(txtPassCu.getText()))
						{
							if (txtPassMoi.getText().equals(txtPassMoiNhapLai.getText()))
							{
								
								
								String UpdateSQL = "";
								UpdateSQL = "ALTER Role " + txtUser.getText() + " ENCRYPTED PASSWORD '" + txtPassMoi.getText() + "';" ;
								UpdateSQL += "update users set pass = ? where id = ? ;" ;
								PreparedStatement ps = c.prepareStatement(UpdateSQL);	
								ps.setString(1, txtPassMoi.getText().toString());
								ps.setInt(2, id );
								 ps.executeUpdate(); 
								   ps.close();
								   st.close();
								   c.close();
								
								
								JOptionPane.showMessageDialog(null, "Đã thay đổi mật khẩu của người dùng: " + txtUser.getText());
							
								
							fLogin.setPass(txtPassMoi.getPassword().toString());
							txtPassCu.setText("");
							txtPassMoi.setText("");
							txtPassMoiNhapLai.setText("");
							
							}
							else
							{
								JOptionPane.showMessageDialog(null, "Mật khẩu xác nhận không giống nhau");
								txtPassMoiNhapLai.requestFocus();
								return;
							}
						}
						else
						{
							JOptionPane.showMessageDialog(null, "Mật khẩu cũ không chính xác");
							txtPassCu.requestFocus();
							return;
						}
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(null, e1);
						
					}
				}
			});
		}
		return btnOk;
	}

	/**
	 * This method initializes btnReset	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnReset() {
		if (btnReset == null) {
			btnReset = new JButton();
			btnReset.setText("Reset");
			btnReset.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					txtPassCu.setText("");
					txtPassMoi.setText("");
					txtPassMoiNhapLai.setText("");
					txtPassCu.requestFocus();
				}
			});
		}
		return btnReset;
	}
	
	/**
	 * @author HT
	 * @param panel
	 */
	public void EmbedLoginPanel(GiscLoginPanel panel)
	{
		this.fLogin=panel;
	}
}  //  @jve:decl-index=0:visual-constraint="16,133"
